package com.py.credit.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.py.credit.service.XypjRemoteBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.ModelDetail;
import com.py.credit.entity.ModelTestChartPoint;
import com.py.credit.entity.ModelTestPc;
import com.py.credit.entity.ModelTestRankForPiePoint;
import com.py.credit.entity.ModelTestScoreForBarPoint;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceModelTestPcFieldsEnum;
import com.py.credit.entity.enums.ResourcePcDetailFieldsEnum;
import com.py.credit.service.ModelTestService;
import com.py.credit.service.UserEvaInfoService;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/modelTest")
public class ModelTestController {

	private final static String FRONT_TABLE_ID = "modelTest";

	@Autowired
	private ModelTestService modelTestService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Autowired
	UserEvaInfoService userEvaInfoService;

		@Value("${absolutepath}")
		private String absolutepath;

	    @Value("${pdfJsPath}")
	    private String pdfJsPath;

	    @Value("${googlePath}")
	    private String googlePath;

	    @Value("${pdfPagePath}")
	    private String pdfPagePath;

	    @Value("${pdfForXypjPagePath}")
	    private String pdfForXypjPagePath;

	    @Value("${pdfForXypjPagePathYz}")
	    private String pdfForXypjPagePathYz;

	/**
	 * @api {get} /modelTest/getTableList.json 获取批次列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 表规则管理
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
	 * 
	 */
	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "condition", required = false) String condition,@RequestParam(value = "roleName", required = true) String roleName,
			@RequestParam(value = "mainType", required = true) String mainType, Page page, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] additionalColumns = { "id" };
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceModelTestPcFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		try {
			List<Map<String, Object>> list  = new ArrayList<Map<String,Object>>();
			if(roleName.equals("部门业务员")) {
				list = modelTestService.getByConditionForPage(showColumns, additionalColumns,
						condition, page, mainType,String.valueOf(userInfo.getId()));
			}else {
				list = modelTestService.getByConditionForPage(showColumns, additionalColumns,
						condition, page, mainType,null);
			}
			
			if (!CollectionUtils.isEmpty(list)) {
				Set<Integer> userIds = new HashSet<Integer>(list.size());
				for (Map<String, Object> m : list) {
					if (null != m && m.containsKey("cjr") && null != m.get("cjr")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("cjr"))));
					}
				}
				xypjRemoteBaseService.matchUserName(list, result, token, userIds, "cjr", "cjrName");
			}
			r = new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), list);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}

	/**
	 * 获取批次初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourceModelTestPcFieldsEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(
			@RequestParam(value = "columns", required = true) String[] columns) {
		RestServiceResult<String> r = new RestServiceResult<String>();
		try {
			MapCache.set(1000 + "_" + FRONT_TABLE_ID, columns);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(
					ResourceModelTestPcFieldsEnum.getAdvancedConditionColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}

	/**
	 * @api {get} /modelTest/getTableList.json 获取企业列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 表规则管理
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
	 * 
	 */
	/*
	 * @RequestMapping(value = "/getEnterPriseTableList.json") public
	 * RestServiceResult<List<Enterprise>> getEnterPriseTableList(
	 * 
	 * @RequestParam(value = "condition", required = false) String
	 * condition,@RequestParam(value = "mainType", required = false) String
	 * mainType, Page page,HttpServletRequest request) {
	 * 
	 * String token = HttpServletHelper.getUserToken(request);
	 * RestServiceResult<List<Enterprise>> result = new
	 * RestServiceResult<List<Enterprise>>(); // 获取当前用户信息
	 * RestServiceResult<SysUser> user =
	 * xypjRemoteBaseService.getCurrentUser(token); SysUser userInfo = null; if
	 * (RestServiceResult.CODE_SUCCESS == user.getCode()) { userInfo =
	 * user.getData(); if (null == userInfo || userInfo.getId() <= 0) {
	 * result.setCode(RestServiceResult.CODE_UNKNOW);
	 * result.setMsg("系统异常，请稍后再试！");
	 * ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
	 * return result; } } else { result.setCode(user.getCode());
	 * result.setMsg(user.getMsg()); return result; } String[] additionalColumns
	 * = {"id,mainType"}; String[] configColumns = (String[])
	 * MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID); List<String>
	 * showColumns = (configColumns == null || configColumns.length == 0) ?
	 * ResourceModelFieldsEnum.getDefaultShowColumnEN() :
	 * Arrays.asList(configColumns); // condition=
	 * "[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
	 * RestServiceResult<List<Enterprise>> r=new
	 * RestServiceResult<List<Enterprise>>(); try{ //List<Map<String, Object>>
	 * tableList =
	 * modelBaseService.getByConditionForPage(showColumns,additionalColumns,
	 * condition, page,kId,areaId,industryId); //r=new
	 * RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(),
	 * tableList); }catch(Exception e){
	 * r.setCode(RestServiceResult.CODE_UNKNOW); r.setMsg("系统异常！"); } return r;
	 * }
	 * 
	 *//**
		 * 获取企业列表初始化列
		 * 
		 * @return
		 *//*
		 * @RequestMapping(value = "/getEnterpriseOptionalColums.json") public
		 * RestServiceResult<List<OptionalColumn>> getEnterpriseOptionalColums()
		 * { RestServiceResult<List<OptionalColumn>> r=new
		 * RestServiceResult<List<OptionalColumn>>(); try{ r=new
		 * RestServiceResult<List<OptionalColumn>>(ResourceEnterpriseFieldsEnum.
		 * getOptionalColumns()); }catch(Exception e){
		 * r.setCode(RestServiceResult.CODE_UNKNOW); r.setMsg("系统异常"); } return
		 * r; }
		 */

	/**
	 * @api {get} /modelTest/getTableList.json 按照批次查询企业得分列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 表规则管理
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
	 * 
	 */
	@RequestMapping(value = "/getEnterPriseScoreByPcTableList.json")
	public RestServiceResult<List<ModelDetail>> getEnterPriseScoreByPcTableList(
			@RequestParam(value = "condition", required = false) String condition,
			@RequestParam(value = "pcId", required = true) String pcId, Page page, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<ModelDetail>> result = new RestServiceResult<List<ModelDetail>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] additionalColumns = { "id,tybm,pcId,reportStatus" };
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID + "EN");
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourcePcDetailFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		RestServiceResult<List<ModelDetail>> r = new RestServiceResult<List<ModelDetail>>();
		try {
			List<ModelDetail> tableList = modelTestService.selectPcDetailByConditionForPage(showColumns,
					additionalColumns, condition, page, pcId);
			r = new RestServiceResult<List<ModelDetail>>(page.getTotalCount(), tableList);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}

	/**
	 * 获取批次详情初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getDetailOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getDetailOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourcePcDetailFieldsEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	/**
	 * 手动选择批次详情展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addDetailShowColunms.json")
	public RestServiceResult<String> addDetailShowColunms(
			@RequestParam(value = "columns", required = true) String[] columns) {
		RestServiceResult<String> r = new RestServiceResult<String>();
		try {
			MapCache.set(1000 + "_" + FRONT_TABLE_ID, columns);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	/**
	 * 获取批次详情高级查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getDetailAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getDetailAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourcePcDetailFieldsEnum.getAdvancedConditionColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}

	/**
	 * 全部测算
	 * 
	 * @return
	 */
	@RequestMapping(value = "/testAll.do")
	public RestServiceResult<Map<String, Object>> testAll(
			@RequestParam(value = "zone", required = false) String zone,
			@RequestParam(value = "industry", required = false) String industry,
			@RequestParam(value = "reportType", required = true) String reportType,
			@RequestParam(value = "mainType", required = true) String mainType,
			@RequestParam(value = "indexScore", required = true) Double indexScore, HttpServletRequest request) {
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<>();
		List<Map<String, String>> modelList = modelTestService.selectModel(zone, industry, reportType, mainType);
		if (modelList == null || modelList.size() == 0 || modelList.size() > 1) {
			result.setCode(-1);
			result.setMsg("未找到相关模型或找到多个模型！");
			return result;
		} else {
			String modelId = modelList.get(0).get("id");
			String scoreType = modelList.get(0).get("scoreType");
			mainType = modelList.get(0).get("mainType");
			ModelTestPc modelTestPc = new ModelTestPc();
			modelTestPc.setId(UuidUtil.getUUid());
			modelTestPc.setIsDel("1");
			modelTestPc.setModelId(modelId);
			modelTestPc.setCjr(String.valueOf(1));
			modelTestPc.setInitIndexScore(indexScore);
			modelTestPc.setMainType(mainType);
			modelTestPc.setReportStatus("0");
		//	new Thread(() -> modelTestService.autoScore(modelTestPc,scoreType, "")).start();
			new Thread(() -> modelTestService.autoScore(modelTestPc,scoreType, "",pdfForXypjPagePathYz,absolutepath,googlePath, pdfJsPath)).start();
//			List<Map> listAll=xypjRemoteBaseService.getAllEnterprise(mainType, "", "");
//			String pch = modelTestService.getpchByPcid(modelTestPc.getId());
//			Map<String,Object> map = new HashMap<>();
//			map.put("pcId", modelTestPc.getId());
//			map.put("pch", pch);
//			result.setData(map);
			return result;
		}

	}

	/**
	 * 全部测算
	 * 
	 * @return
	 */
	@RequestMapping(value = "/testBySelected.do")
	public RestServiceResult<Map<String, Object>> testBySelected(
			@RequestParam(value = "zone", required = false) String zone,
			@RequestParam(value = "industry", required = false) String industry,
			@RequestParam(value = "reportType", required = true) String reportType,
			@RequestParam(value = "mainType", required = true) String mainType,
			@RequestParam(value = "indexScore", required = true) Double indexScore,
			@RequestParam(value = "selectedList", required = true) String selectedList, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		/*
		 * List<Map> list = JSON.parseObject(selectedList, new
		 * TypeReference<List<Map>>() { });
		 */
		List<Map<String, String>> modelList = modelTestService.selectModel(zone, industry, reportType, mainType);
		if (modelList == null || modelList.size() == 0 || modelList.size() > 1) {
			result.setCode(-1);
			result.setMsg("未找到相关模型或找到多个模型！");
			return result;
		} else {
			String modelId = modelList.get(0).get("id");
			String scoreType = modelList.get(0).get("scoreType");
			mainType = modelList.get(0).get("mainType");
			ModelTestPc modelTestPc = new ModelTestPc();
			modelTestPc.setId(UuidUtil.getUUid());
			modelTestPc.setIsDel("1");
			modelTestPc.setModelId(modelId);
			modelTestPc.setCjr(String.valueOf(userInfo.getId()));
			modelTestPc.setInitIndexScore(indexScore);
			modelTestPc.setMainType(mainType);
			modelTestPc.setReportStatus("0");
			new Thread(() -> modelTestService.autoScore(modelTestPc,scoreType, selectedList,pdfForXypjPagePathYz,absolutepath,googlePath, pdfJsPath)).start();
			// List<Map>listAll=xypjRemoteBaseService.getAllEnterprise();
//			String pch = modelTestService.getpchByPcid(modelTestPc.getId());
//			Map<String,Object> map = new HashMap<>();
//			map.put("pcId", modelTestPc.getId());
//			map.put("pch", pch);
//			result.setData(map);
			return result;
		}

	}

	@RequestMapping(value = "/toNormalDistributionChart.json", method = RequestMethod.POST)
	@ApiOperation(value = "正态分布", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "rate", value = "选择的比例", required = true) })
	public RestServiceResult<List<ModelTestChartPoint>> toNormalDistributionChart(
			@RequestParam(value = "pcId", required = true) String pcId,
			@RequestParam(value = "rate", required = true) String rate, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<ModelTestChartPoint>> result = new RestServiceResult<List<ModelTestChartPoint>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		result.setData(modelTestService.toNormalDistributionChart(pcId, rate));
		return result;
	}

	@RequestMapping(value = "/toRankForPieChart.json", method = RequestMethod.POST)
	@ApiOperation(value = "信用评价等级分布图", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true)

	})
	public RestServiceResult<List<ModelTestRankForPiePoint>> toRankForPieChart(
			@RequestParam(value = "pcId", required = true) String pcId, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<ModelTestRankForPiePoint>> result = new RestServiceResult<List<ModelTestRankForPiePoint>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		result.setData(modelTestService.toRankForPieChart(pcId));
		return result;

	}

	@RequestMapping(value = "/toScoreForBarChart.json", method = RequestMethod.POST)
	@ApiOperation(value = "信用评价分值分布图", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true)

	})
	public RestServiceResult<List<ModelTestScoreForBarPoint>> toScoreForBarChart(
			@RequestParam(value = "pcId", required = true) String pcId, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<ModelTestScoreForBarPoint>> result = new RestServiceResult<List<ModelTestScoreForBarPoint>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		result.setData(modelTestService.toScoreForBarChart(pcId));
		return result;

	}

	@RequestMapping(value = "/viewScoreDetail.json", method = RequestMethod.POST)
	@ApiOperation(value = "查看得分明细", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "tybm", value = "企业统一编码", required = true)

	})
	public RestServiceResult<List<Map>> viewScoreDetail(@RequestParam(value = "pcId", required = true) String pcId,
			@RequestParam(value = "tybm", required = true) String tybm, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;

	}

	@RequestMapping(value = "/testByUpload.do", method = RequestMethod.POST)
	@ApiOperation(value = "", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "pcId", value = "批次id", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "string", name = "tybm", value = "企业统一编码", required = true)

	})

	public RestServiceResult<String> testByUpload(@RequestParam(value = "batchId", required = true) String batchId,
			@RequestParam(value = "zone", required = false) String zone,
			@RequestParam(value = "industry", required = false) String industry,
			@RequestParam(value = "reportType", required = true) String reportType,
			@RequestParam(value = "mainType", required = true) String mainType,
			@RequestParam(value = "indexScore", required = true) Double indexScore, HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
			try {
				List<Map<String, String>> modelList = modelTestService.selectModel(zone, industry, reportType,
						mainType);
				if (modelList == null || modelList.size() == 0 || modelList.size() > 1) {
					result.setCode(-1);
					result.setMsg("未找到相关模型或找到多个模型！");
					return result;
				} else {
					String modelId = modelList.get(0).get("id");
					String scoreType = modelList.get(0).get("scoreType");
					mainType = modelList.get(0).get("mainType");
					ModelTestPc modelTestPc = new ModelTestPc();
					modelTestPc.setId(UuidUtil.getUUid());
					modelTestPc.setIsDel("1");
					modelTestPc.setModelId(modelId);
					modelTestPc.setCjr(String.valueOf(userInfo.getId()));
					modelTestPc.setInitIndexScore(indexScore);
					modelTestPc.setMainType(mainType);
					modelTestService.autoScoreUpload(modelTestPc,scoreType, batchId, pdfForXypjPagePathYz, absolutepath, googlePath, pdfJsPath);
					// List<Map>listAll=xypjRemoteBaseService.getAllEnterprise();
					return result;
				}
				// result.setData("");
			} catch (ServiceException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}
	
	
	@RequestMapping(value = "/getEvailInfoScore.json", method = RequestMethod.GET)
	public RestServiceResult<String> getEvailInfoScore(
			@RequestParam(value = "tybm", required = true) String tybm) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		try {
			String data = modelTestService.getEvailInfoScore(tybm);
			result.setData(data);
		} catch (Exception e) {
        result.setMsg("一站式查询评价分数失败");
		}
		return result;
	}
	@RequestMapping(value = "/getxydjInfo.json", method = RequestMethod.POST)
	public RestServiceResult< Map<String, Object>> getxydjInfo(
			@RequestParam(value = "tybm", required = true) String tybm,
			@RequestParam(value = "pcId", required = true) String pcId) {
		RestServiceResult< Map<String, Object>> result = new RestServiceResult< Map<String, Object>>();
		try {
			 Map<String, Object> data = modelTestService.getxydjInfo(tybm,pcId);
			result.setData(data);
		} catch (Exception e) {
        result.setMsg("查询信息失败");
		}
		return result;
	}
}
